﻿using Furion;
using net8.Models.ShangPin;
using net8.Models.Upload;
using net8.Models.Wangzhan;
using net8.Models.XiTong;
using SqlSugar;

namespace net8.Models
{
    /// <summary>
    /// 数据库帮助类
    /// </summary>
    public class DbHelper
    {
        public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = App.Configuration["pgsql"],//连接符字串
            DbType = DbType.PostgreSQL,//数据库类型
            IsAutoCloseConnection = true, //不设成true要手动close
            ConfigureExternalServices = new ConfigureExternalServices()
            {
                EntityService = (s, p) =>
                {
                    p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);
                    if (!p.IsPrimarykey)
                    {
                        p.IsNullable = true;
                    }
                },
                EntityNameService = (s, p) =>
                {
                    p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);
                },
                SplitTableService = new yyyyMMService()
            }
        },
          db =>
          {
              //(A)全局生效配置点，一般AOP和程序启动的配置扔这里面 ，所有上下文生效
              //调试SQL事件，可以删掉
              db.Aop.OnLogExecuting = (sql, pars) =>
              {
                  //Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响

                  //获取原生SQL推荐 5.1.4.63  性能OK
                  string aa = UtilMethods.GetNativeSql(sql, pars);

                  //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                  string bb = UtilMethods.GetSqlString(DbType.SqlServer, sql, pars);

              };

              db.Aop.DataExecuting = (oldValue, entityInfo) =>
              {
                  if ("AddTime" == entityInfo.PropertyName)
                  {
                      entityInfo.SetValue(DateTime.Now);
                  }
                  if ("UpdateTime" == entityInfo.PropertyName)
                  {
                      entityInfo.SetValue(DateTime.Now);
                  }
              };

              //多个配置就写下面
              //db.Ado.IsDisableMasterSlaveSeparation=true;

              //注意多租户 有几个设置几个
              //db.GetConnection(i).Aop
          });

        public static void Init()
        {
            Db.DbMaintenance.CreateDatabase();
            Db.CodeFirst.InitTables(typeof(XtUser), typeof(XTLog), typeof(XtCompany), typeof(XtMenu), typeof(XtUserRole));
            Db.CodeFirst.InitTables(typeof(XtPermission),typeof(XtRole));
            Db.CodeFirst.InitTables(typeof(UpFile), typeof(UpRelation), typeof(SpShangPin));
            Db.CodeFirst.InitTables(typeof(WZNews),typeof(WzType),typeof(WzWenDang));

            Db.CodeFirst.SplitTables().InitTables<MySpliteTest>();
        }
    }
}
